<?php


namespace App\Model\Logic;


use App\Exception\HttpExecption;
use Swoft\Bean\Annotation\Mapping\Bean;
use Swoft\Validator\Exception\ValidatorException;

/**
 * 文件上传
 * @Bean()
 * @package App\Model\Logic
 */
class UploadLogic
{
    /**
     * 文件上传
     * @param $file
     */
    public function upload($file){
        //文件验证
        $this->checkFile($file);
        $fn = $file->getClientFilename();
        //取文件的扩展名
        $ext = substr($fn,strrpos($fn,"."));
        // 生成文件名
        $filename = md5(time().$fn).$ext;
        //移动文件到上传目录
        $file->moveTo("public/uploads/".$filename);
        throw new HttpExecption("上传成功",0,['img'=>"/uploads/".$filename]);
    }

    private function checkFile($file){
        try {
            validate(["file" => $file], "FileValidator");
        } catch (ValidatorException $e) {
            throw new HttpExecption($e->getMessage(),1,[],200);
        }
        $mime = getimagesize($file->getFile());
        if(!$mime){
            throw new HttpExecption("文件类型不被允许",1,[],200);
        }

        if(!in_array($mime['mime'],["image/gif","image/png","image/jpeg"])){
            throw new HttpExecption("文件类型不被允许",1,[],200);
        }
    }
}
